package com.mini.grpc.serialization;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 字符串序列化器
 * 用于将字符串与字节流之间进行转换
 */
public class StringMarshaller implements Marshaller<String> {
    
    /**
     * 单例实例
     */
    public static final StringMarshaller INSTANCE = new StringMarshaller();
    
    private StringMarshaller() {
        // 私有构造函数，使用单例模式
    }
    
    @Override
    public InputStream stream(String value) {
        if (value == null) {
            return new ByteArrayInputStream(new byte[0]);
        }
        byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
        return new ByteArrayInputStream(bytes);
    }
    
    @Override
    public String parse(InputStream stream) {
        try {
            byte[] bytes = stream.readAllBytes();
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse string from stream", e);
        }
    }
} 